﻿using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using LiftHub.Data;
using LiftHub.Services;
using LiftHub.ViewModels.Pages;
using LiftHub.Views;

namespace LiftHub.Controls;

public partial class NoteItemControl : UserControl
{
    private readonly bool NewOne;
    private readonly int Id = -1;

    public NoteItemControl(Note? note = null, bool newOne = false)
    {
        InitializeComponent();
        NewOne = newOne;
        HeaderTextBox = this.FindControl<TextBox>("HeaderTextBox");
        ContextBox = this.FindControl<TextBox>("ContextBox");
        if (newOne || note == null)
        {
            NewOne = true;
            return;
        }

        Id = note.Key;
        HeaderTextBox.Text = note.Title;
        ContextBox.Text = note.Context;
    }

    private void BackClick(object? sender, RoutedEventArgs e)
    {
        if (DataContext is not NotesPageModel model) return;
        var item = new Note() { Context = ContextBox.Text, Title = HeaderTextBox.Text };
        if (NewOne)
        {
            model.Add(item);
        }
        else
        {
            item.Key = Id;
            model.Change(item);
        }

        var main = ViewService.GetView<MainView>(this);
        if (main == null) return;
        main.Navigate(model);
    }

    private void DeleteClick(object? sender, RoutedEventArgs e)
    {
        if (!NewOne)
        {
            if (DataContext is not NotesPageModel model) return;
            model.Remove(Id);
        }

        var main = ViewService.GetView<MainView>(this);
        if (main == null) return;
        main.Navigate(DataContext);
    }
}